import React, {useState,useEffect} from 'react' ;
import Details from './detail';
import Replies from './replies';
import { useParams } from 'react-router';
import {Alert} from 'antd';

export default function Topic(props){
    // console.log(props);
    // const {id} = props.match.params;
    const {id}=useParams();
    console.log(id);
    let [loading,setloading] = useState(true);
    let [iserror,setiserror] = useState(false);
    let [error_msg,seterror_msg]=useState('');
    let [data,setData]=useState('');
    
    useEffect(()=>{
        fetch(`https://cnodejs.org/api/v1/topic/${id}`)
        .then(data=>data.json())
        .then(data=>{
            setloading(false);
            if(data.success){
                setData(data.data);
            }
            else{
                setiserror(true);
                seterror_msg(data.error_msg);
            }
            // console.log(data);
            // 状态
            // 1. 正常状态
            // 2. 出错
            // 3. loading
        })
    },[id])

    // 父组件负责发送请求 data

    return (
        <>
            {iserror?(
                <Alert 
                    message={"请求出错了"} 
                    closable 
                    type="error" 
                    description={
                    <>
                        <p>{error_msg}</p>
                        <p>点击关闭返回上一步</p>
                    </>
                } />
            ):(
                <>
                    <Details data={data} loading={loading} />
                </>
            )}
            
            <Replies />
        </>
    )
}